<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/10/9
 * Time: 14:19
 */

namespace app\index\controller;


use app\service\TaskService;
use Redis\Redis;
use think\Db;

class BizCreation extends Common
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询服务/商品分类
     */
    function getClassification()
    {
        # 类型 0=>全部 1=>商品 2=>服务
        $type = input('post.type') ?? 0;
        # 一级分类id(用于查询二级分类)
        $classId = input('post.class_id') ?? 0;
        # 操作标识  creation-->添加/修改页面展示
        $mark = trim(input('post.mark'));
        # redis
        $redis = $this->_Redis;
        # 商品分类初始化
        $pro = array();
        # 服务分类初始化
        $service = array();
        $_topStatus = true;
        if ($type == 1) {
            #商品
            $pro = $redis->hGetJson('getClassification' . $classId, 'pro');
//            if (empty($pro)) {
            $pro = Db::table('pro_class')->field("id,id label,class_title text,1 type")
                ->where(array('class_id' => $classId))
                ->where(array('status' => 1, 'class_type' => 2))
                ->select();
            $redis->hSetJson('getClassification' . $classId, 'pro', $pro);
//            }
            if ($mark != 'creation') {
                if ($classId == 0) {
                    $_topStatus = false;
                    array_unshift($pro, array("label" => 0, "text" => "全部", "type" => 1, 'child' => array(array("label" => 0, "text" => "全部", "type" => 1))));
                } else {
                    array_unshift($pro, array("label" => 0, "text" => "全部", "type" => 1));
                }
            }
//            else {
//                $pro = array_column($pro, NULL, 'label');
//                return array('status' => true, 'data' => $pro);
//            }
        }
        if ($type == 2 or $type == 0) {
            #服务
            $service = $redis->hGetJson('getClassification' . $classId, 'service');
//            if (empty($service)) {
//                $_idWhere = "id in (select service_class_id from service where biz_pid =$bizId)";
            $service = Db::table('service_class')->field("id label,id value,service_class_title text,2 type")
                ->where(array("service_class_pid" => $classId))
                ->where(array('is_del' => 2))
//                    ->where($_idWhere)
                ->select();
            $redis->hSetJson('getClassification' . $classId, 'service', $service);
//            }
            if ($mark != 'creation') {
                if ($classId == 0) {
                    if ($_topStatus) {
                        array_unshift($service, array("label" => 0, "text" => "全部", "type" => 2, 'child' => array(array("label" => 0, "text" => "全部", "type" => 2))));
                    }
                } else {
                    array_unshift($service, array("label" => 0, "text" => "全部", "type" => 2));
                }
            }
//            else {
//                $service = array_column($service, NULL, 'label');
//                return array('status' => true, 'data' => $service);
//            }
        }
        $_return = array_merge_recursive($pro, $service);
        return array('status' => true, 'data' => $_return);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询门店/服务列表信息
     */
    function listInfo()
    {
        # 门店id
        $bizId = $this->bizId;
        # 一级分类id
        $classId = input('post.class_id') ?? 0;
        # 二级分类id
        $classPid = input('post.class_pid') ?? 0;
        # 状态筛选(0=>全部 1=>销售中 2=>审核中 3=>未通过 4=>已下架)
        $auditStatus = input('post.audit_status');
        # 类型筛选(0=>全部 1=>折扣商品 2=>非折扣商品 3=>折扣服务 4=>非折扣服务,5=>全部商品 6=>全部服务)
        $type = input('post.type') ?? 0;
        # 名称/关键词搜索
        $search = input('post.search_info');
        # 页数
        $page = input('post.page') ?? 0;
        # 每页数量(商品/服务)
        $listRows = 5;
        # 页码
        $pageMark = $page * $listRows;
        # 商品信息数组
        $pro = array();
        # 服务信息数组
        $service = array();
        # 状态筛选---where
        $status_where = array();
        # 类型筛选---where
        $type_where = array();
        # 名称/关键词搜索
        $_fieldWhere = null;
        $_searchWhere = null;
        $_field = '';
        # class 分类筛选
        $class_where = array();

        $_keyWeightOrder = array();
        # 查询服务/商品 信息

        # 查询服务列表
        # 筛选状态判断
        if (!empty($auditStatus)) {
            if ($auditStatus == 1) {
                # 销售中 (审核已通过并且已上架)
                $status_where = array('audit_status' => 2, 'service_status' => 1);
            } elseif ($auditStatus == 2) {
                # 审核中
                $status_where = array('audit_status' => 1);
            } elseif ($auditStatus == 3) {
                # 审核未通过
                $status_where = array('audit_status' => 3);
            } elseif ($auditStatus == 4) {
                # 已下架(审核通过且已下架)
                $status_where = array('audit_status' => 2, 'service_status' => 0);
            }
        }
        # 类型筛选判断
        if (!empty($type)) {
            if ($type == 1) {
                # 折扣商品
                $type_where = array('is_discount' => 1, 'add_type' => 1);
            } elseif ($type == 2) {
                # 非折扣商品
                $type_where = array('is_discount' => 2, 'add_type' => 1);
            } elseif ($type == 3) {
                # 折扣服务
                $type_where = array('is_discount' => 1, 'add_type' => 2);
            } elseif ($type == 4) {
                # 非折扣服务
                $type_where = array('is_discount' => 2, 'add_type' => 2);
            }
        }
        # 分类筛选
        if (!empty($classId)) {
            # 一级分类筛选
            $classInfo = Db::table('service_class')->field('id')->where('service_class_pid = ' . $classId . ' or id = ' . $classId)->select();
            if (!empty($classInfo)) {
                $classIdInfo = implode(',', array_column($classInfo, 'id'));
                $class_where = "service_class_id in (" . $classIdInfo . ")";
            }
        }
        if (!empty($classPid)) {
            # 二级分类筛选
            $class_where = "service_class_id = " . $classPid;
        }
        # 判断服务查询个数
//            if (count($pro) < 5) {
//                $listRows = $listRows * 2 - count($pro);
//            }
        # 名称/关键词 搜索
        if (!empty($search) and $search != 'false' and $search != 'undefined') {
            $_field = 'if(service_title like "%' . $search . '%" or service_keyborder like "%' . $search . '%",1,0)';
            $_searchWhere = '(locate("' . $search . '",service_title) or locate("' . $search . '",service_keyborder))';
            $_num = mb_strlen($search);
            $searchInfo = preg_split("//u", $search, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($searchInfo as $v) {
                if (is_null($_searchWhere)) {
                    $_searchWhere = '';
                } else {
                    $_searchWhere .= ' or (locate("' . $v . '",service_title) or locate("' . $v . '",service_keyborder))';
                }
                $_field .= ' + if((service_title like "%' . $v . '%" or service_keyborder like "%' . $v . '%"),1,0)';
            }
            $_field = '(' . $_field . ')';
            $_fieldWhere = '(' . $_field . '>= ' . $_num . ')';
            $_field = ',' . $_field . ' keyWeight';
            $_keyWeightOrder = array('keyWeight' => 'desc');
        }
        $service = Db::table('service s')
            ->field('id,add_type,service_title title,if(locate("http",service_image)=0,CONCAT("' . config('ecarcoo.imgUrl') . '",service_image),service_image) img,
            show_recommend,show_recommend_title,
                is_discount,service_keyborder label_info,audit_status,if(service_status=1,1,2) status,2 info_type,
                (select count(id) from order_server where server_id=s.id and status = 6 and custommark = 1) buy_num,
                (select sum(price) from order_server where server_id=s.id and status = 6 and custommark = 1) sales_price,
                (select service_class_title from service_class where id = s.service_class_id) class_second,
                (select service_class_title from service_class where id =(select service_class_id from service_class where id = s.service_class_id)) class_first,
                (select if(min(discount)= max(discount),(max(discount)),(CONCAT_WS("~",convert(min(discount),decimal(10,2)),max(discount)))) from service_car_mediscount 
                where service_id=s.id and service_type=1 and  biz_id=' . $bizId . ') online_price,
                (select if(min(discount)= max(discount),(max(discount)),(CONCAT_WS("~",convert(min(discount),decimal(10,2)),max(discount)))) from service_car_mediscount 
                where service_id=s.id and service_type=2 and  biz_id=' . $bizId . ') biz_price,
            (select if((min(discount)*(select discount from service_mediscount where member_level=9 and service_id=s.id))= max(discount),(max(discount)),
            (CONCAT_WS("~",convert((min(discount)*(select discount from service_mediscount where member_level=9 and service_id=s.id)),decimal(10,2)),max(discount)))) from service_car_mediscount 
                where service_id=s.id and biz_id=' . $bizId . ') discount_price ' . $_field)
            ->where(array('s.biz_pid' => $bizId, 's.is_del' => 2))
            ->where($status_where)
            ->where($type_where)
            ->where($class_where)
            ->where($_fieldWhere)
            ->where($_searchWhere)
            ->order($_keyWeightOrder)
            ->order(array('service_order' => 'asc', 'show_recommend' => 'asc', 'id' => 'desc'))
            ->limit($pageMark, $listRows)
            ->select();

        # 合并 商品/服务 信息
        $_return = $service;
        if (!empty($_return)) {
            foreach ($_return as $k => $v) {
                if ($v['show_recommend'] == 1) {
                    $_return[$k]['show_recommend_tips'] = '推荐中';
                } else {
                    $_return[$k]['show_recommend_tips'] = '立即推荐';
                }
                $_return[$k]['label_info'] = array_filter(explode('，', $v['label_info']));
                $_return[$k]['sales_price'] = getsPriceFormat($v['sales_price']);
                if ($v['audit_status'] == 1) {
                    $_return[$k]['status_mark'] = 2;
                    $_return[$k]['status_text'] = '审核中';
                } elseif ($v['audit_status'] == 2 and $v['status'] == 1) {
                    $_return[$k]['status_mark'] = 1;
                    $_return[$k]['status_text'] = '销售中';
                } elseif ($v['audit_status'] == 2 and $v['status'] == 2) {
                    $_return[$k]['status_mark'] = 4;
                    $_return[$k]['status_text'] = '已下架';
                } else {
                    $_return[$k]['status_mark'] = 3;
                    $_return[$k]['status_text'] = '未通过';
                }
            }
        }
        array_multisort(array_column($_return, 'status_mark'), SORT_ASC, $_return);
        array_multisort(array_column($_return, 'show_recommend'), SORT_ASC, $_return);
        # 查询创建商品权限/创建商品数量 and service_status = 1
        $createPro = Db::table('biz')
            ->field('create_pro,create_pro_num,
            (select count(id) from service where biz_pid = ' . $bizId . ' and audit_status != 3  and is_del=2) exist_num')
            ->where(array('id' => $bizId))
            ->find();
        $createPro['surplus_num'] = intval($createPro['create_pro_num']) - intval($createPro['exist_num']);
        if ($createPro['surplus_num'] < 0) {
            $createPro['surplus_num'] = 0;
        }
        $redis = new Redis();
        $redis->hDel('CooperativeCreation', strval($this->bizId));
        return array('status' => true, 'data' => $_return, 'create_pro' => $createPro);
    }

    function createPro()
    {
        # 查询创建商品权限/创建商品数量 and service_status = 1
        $createPro = Db::table('biz')
            ->field('create_pro,create_pro_num,
            (select count(id) from service where biz_pid = ' . $this->bizId . ' and audit_status != 3  and is_del = 2) exist_num')
            ->where(array('id' => $this->bizId))
            ->find();
        $createPro['surplus_num'] = intval($createPro['create_pro_num']) - intval($createPro['exist_num']);
        return array('status' => true, 'create_pro' => $createPro);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询商品详情
     */
    function proDetail()
    {
        # 查看商品详情
        # 商品id
        $proId = input('post.id');
        if (empty($proId)) {
            return array('status' => false, 'msg' => '系统错误-001');
        }
        # 查询商品信息
        $info = Db::table('biz_pro')
            ->field('biz_pro_title,biz_pro_class_id,(select class_id from pro_class where id = biz_pro_class_id) class_pid,
            biz_pro_key,pro_statement,biz_pro_price,biz_pro_online,is_discount,discount_type,biz_pro_showshop,
            is_maintain,is_repair,is_warranty,
            biz_pro_image,biz_pro_picurl,biz_pro_detailimage,biz_pro_status,audit_status')
            ->where(array('biz_pid' => $this->bizId))
            ->find();
        # 关键词处理-转成数组
        $info['label_info'] = explode('，', $info['biz_pro_key']);
        # 图片处理
        $info['biz_pro_picurl_arr'] = strlen($info['biz_pro_picurl']) > 0 ? explode(',', $info['biz_pro_picurl']) : [];
        $info['biz_pro_detailimage_arr'] = strlen($info['biz_pro_detailimage']) > 0 ? explode(',', $info['biz_pro_detailimage']) : [];
        # 查询关联保养记录
        $info['maintain_log'] = Db::table('biz_pro_log')->where(array('pro_id' => $proId, 'log_type' => 1))->select();
        # 查询关联维修记录
        $info['repair_log'] = Db::table('biz_pro_log')->where(array('pro_id' => $proId, 'log_type' => 2))->select();
        # 查询关联质保记录
        $info['warranty_log'] = Db::table('biz_pro_log')->where(array('pro_id' => $proId, 'log_type' => 3))->select();
        # 查询历史标签记录
        $info['keyword_history'] = array();
        $keywordHistory = Db::table('biz_pro')
            ->field('biz_pro_key')
            ->where(array('biz_pid' => $this->bizId))
            ->order(array('id' => 'desc'))
            ->limit(10)
            ->select();
        if (!empty($keywordHistory)) {
            $_hArr = array();
            foreach ($keywordHistory as $k => $v) {
                $history = explode('，', $v['biz_pro_key']);
                foreach ($history as $hk => $hv) {
                    if (!empty($hv) and !in_array($hv, $_hArr)) {
                        array_push($info['keyword_history'], array('title' => $hv, 'status' => false));
                        array_push($_hArr, $hv);
                    }
                }
            }
            $info['keyword_history'] = array_unique(array_filter($info['keyword_history']));
        }
        return array('status' => true, 'msg' => '查询成功', 'data' => $info);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询服务详情
     */
    function serviceDetail()
    {
        # 查看服务详情
        # 服务id
        $serviceId = input('post.id');
        if (empty($serviceId)) {
            return array('status' => false, 'msg' => '系统错误-001');
        }
        # 查询服务信息
        $info = Db::table('service')
            ->field('add_type,service_title,service_class_id,class_pid,service_keyborder,service_statement,is_car_level,service_time,
            is_discount,discount_type,is_display,is_maintain,is_repair,is_warranty,
            if(locate("http",service_image)=0,CONCAT("' . config('ecarcoo.imgUrl') . '",service_image),service_image) service_image,
            service_picurl,service_context,service_status,audit_status')
            ->where(array('id' => $serviceId))
            ->find();
        # 关键词处理-转成数组
        $info['label_info'] = explode('，', $info['service_keyborder']);
        # 图片处理
        $info['service_picurl_arr'] = strlen($info['service_picurl']) > 0 ? explode(',', $info['service_picurl']) : [];
        $info['service_context_arr'] = strlen($info['service_context']) > 0 ? explode(',', $info['service_context']) : [];
        # 查询门店价格
        $info['biz_price'] = Db::table('service_car_mediscount')
            ->field('id,car_level_id,discount')
            ->where(array('biz_id' => $this->bizId, 'service_type' => 2, 'service_id' => $serviceId))
            ->order(array('car_level_id' => 'asc'))
            ->select();
        # 查询线上价格
        $info['online_price'] = Db::table('service_car_mediscount')
            ->field('id,car_level_id,discount')
            ->where(array('biz_id' => $this->bizId, 'service_type' => 1, 'service_id' => $serviceId))
            ->order(array('car_level_id' => 'asc'))
            ->select();
        # 查询关联保养记录
        $info['maintain_log'] = Db::table('service_log')->where(array('service_id' => $serviceId, 'log_type' => 1))->find();
        # 查询关联维修记录
        $info['repair_log'] = Db::table('service_log')->where(array('service_id' => $serviceId, 'log_type' => 2))->find();
        # 查询关联质保记录
        $info['warranty_log'] = Db::table('service_log')->where(array('service_id' => $serviceId, 'log_type' => 3))->find();
        # 查询历史标签记录
        $info['keyword_history'] = array();
        $keywordHistory = Db::table('service')
            ->field('service_keyborder')
            ->where(array('biz_pid' => $this->bizId))
            ->order(array('id' => 'desc'))
            ->limit(10)
            ->select();
        if (!empty($keywordHistory)) {
            $_hArr = array();
            foreach ($keywordHistory as $k => $v) {
                $history = explode('，', $v['service_keyborder']);
                foreach ($history as $hk => $hv) {
                    if (!empty($hv) and !in_array($hv, $_hArr)) {
                        array_push($info['keyword_history'], array('title' => $hv, 'status' => false));
                        array_push($_hArr, $hv);
                    }
                }
            }
        }
        return array('status' => true, 'msg' => '查询成功', 'data' => $info);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 历史标签记录
     */
    function keywordHistory()
    {
        # 查询历史标签记录
        $keyword_history = array();
        $keywordHistory = Db::table('service')
            ->field('service_keyborder')
            ->where(array('biz_pid' => $this->bizId))
            ->order(array('id' => 'desc'))
            ->limit(10)
            ->select();
        if (!empty($keywordHistory)) {
            $_hArr = array();
            foreach ($keywordHistory as $k => $v) {
                $history = explode('，', $v['service_keyborder']);
                foreach ($history as $hk => $hv) {
                    if (!empty($hv) and !in_array($hv, $_hArr)) {
                        array_push($keyword_history, array('title' => $hv, 'status' => false));
                        array_push($_hArr, $hv);
                    }
                }
            }
        }
        return array('status' => true, 'msg' => '查询成功', 'data' => $keyword_history);
    }

    function proModify()
    {
        # 商品详情修改
        # 服务id
        $proId = input('post.id');
        # 接收商品信息
        $info = input('post.info');
        if (empty($info)) {
            return array('status' => false, 'msg' => '系统错误-0021');
        }
        # 信息空值验证
        $validateArr = [
            [
                'key_name' => 'biz_pro_title',
                'error_msg' => '商品名称不能为空'
            ],
            [
                'key_name' => 'biz_pro_class_id',
                'error_msg' => '商品分类不能为空'
            ],
            [
                'key_name' => 'pro_statement',
                'error_msg' => '轮播声明不能为空'
            ],
            [
                'key_name' => 'biz_price',
                'error_msg' => '门店价格不能为空'
            ],
            [
                'key_name' => 'online_price',
                'error_msg' => '线上价格不能为空'
            ],
            [
                'key_name' => 'bizimage',
                'error_msg' => '缩略图不能为空'
            ],
            [
                'key_name' => 'banner',
                'error_msg' => '主图不能为空'
            ],
            [
                'key_name' => 'detailimg',
                'error_msg' => '详情图不能为空'
            ]
        ];
        foreach ($validateArr as $k => $v) {
            if (empty($info[$v['key_name']])) {
                return array('status' => false, 'msg' => $v['error_msg']);
            }
        }
        # 处理图片信息
        # 缩略图上传  service_image
        $res = uploadBase($info['bizimage'], 'creation');
        if (is_array($res)) {
            return $res;
        }
        $info['biz_pro_image'] = $res;
        # banner 上传  service_picurl
        foreach ($info['banner'] as $k => $v) {
            $res = uploadBase($v, 'creation');
            if (is_array($res)) {
                return $res;
            }
            $info['biz_pro_picurl'][$k] = $res;
        }
        $info['biz_pro_picurl'] = implode(',', $info['biz_pro_picurl']);
        # 详情图上传  service_context
        foreach ($info['detailimg'] as $k => $v) {
            $res = uploadBase($v, 'creation');
            if (is_array($res)) {
                return $res;
            }
            $info['biz_pro_detailimage'][$k] = $res;
        }
        $info['biz_pro_detailimage'] = implode(',', $info['biz_pro_detailimage']);
        # 关键词数组--转 字符串
        $service_keyborder = implode('，', $info['label_info']);

        if (!empty($proId)) {
            # 判断上下架状态,如果是下架状态,直接修改状态不需要保存修改信息
            if ($info['biz_pro_status'] != 1) {
                Db::table('biz_pro')->where(array('id' => $proId))->update(array('biz_pro_status' => 2));
                return array('status' => true, 'msg' => '成功下架');
            } else {
                # 状态修改为审核中
                Db::table('biz_pro')->where(array('id' => $proId))->update(array('audit_status' => 1));
                # 添加修改审核信息
                $auditId = Db::table('audit_creation')->insertGetId(array(
                    'type' => 2,
                    'pid' => $proId,
                    'biz_id' => $this->bizId,
                    'state' => 1,
                    'add_time' => date('Y-m-d H:i:s'),
                    'mark' => 2
                ));
                $this->_Redis->hSetJson('BizCreation', strval($auditId), $info);
                return array('status' => true, 'msg' => '已提交审核');
            }
        } else {
            # 创建商品信息

            # biz_pro 信息添加
            $proId = Db::table('biz_pro')->insertGetId(array(
                'biz_pro_title' => $info['biz_pro_title']
            ));
        }
    }

    /**
     * @return array|mixed|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 服务创建/修改
     */
    function serviceModify()
    {
        # 查询门店差创建商品权限
        if ($this->bizId != 692 and $this->bizId != 408) {
            $createPro = Db::table('biz')
                ->field('create_pro')
                ->where(array('id' => $this->bizId))
                ->value('create_pro');
            if ($createPro == 2) {
                return array('status' => false, 'msg' => '权限未开启');
            }
        }
        # 服务详情修改
        # 服务id
        $serviceId = input('post.id');
        # 接收服务信息
        $info = input('post.info');
        if (empty($info)) {
            return array('status' => false, 'msg' => '系统错误-0021');
        }
        # 信息空值验证
        $validateArr = [
            [
                'key_name' => 'service_title',
                'error_msg' => '标题不能为空'
            ],
            [
                'key_name' => 'service_class_id',
                'error_msg' => '服务分类不能为空'
            ],
//            [
//                'key_name' => 'service_time',
//                'error_msg' => '服务时长不能为空'
//            ],
            [
                'key_name' => 'biz_price',
                'error_msg' => '门店价格不能为空'
            ],
//            [
//                'key_name' => 'online_price',
//                'error_msg' => '线上价格不能为空'
//            ],
            [
                'key_name' => 'bizimg',
                'error_msg' => '缩略图不能为空'
            ],
//            [
//                'key_name' => 'banner',
//                'error_msg' => '主图不能为空'
//            ],
//            [
//                'key_name' => 'detailimg',
//                'error_msg' => '详情图不能为空'
//            ]
        ];
        foreach ($validateArr as $k => $v) {
            if (empty($info[$v['key_name']])) {
                return array('status' => false, 'msg' => $v['error_msg']);
            }
        }
        # 处理图片信息
        # 缩略图上传  service_image
        $res = uploadBase($info['bizimg'], 'creation');
        if (is_array($res)) {
            return $res;
        }
        $info['service_image'] = $res;
        # banner 上传  service_picurl
//        foreach ($info['banner'] as $k => $v) {
//            $res = uploadBase($v, 'creation');
//            if (is_array($res)) {
//                return $res;
//            }
//            $info['service_picurl'][$k] = $res;
//        }
//        $info['service_picurl'] = implode(',', $info['service_picurl']);
//        # 详情图上传  service_context
//        foreach ($info['detailimg'] as $k => $v) {
//            $res = uploadBase($v, 'creation');
//            if (is_array($res)) {
//                return $res;
//            }
//            $info['service_context'][$k] = $res;
//        }
//        $info['service_context'] = implode(',', $info['service_context']);
        # 关键词数组--转 字符串
        $service_keyborder = implode('，', $info['label_info']);
        if (!empty($serviceId)) {
            # 判断上下架状态,如果是下架状态,直接修改状态不需要保存修改信息
            if ($info['service_status'] != 1) {
                Db::table('service')->where(array('id' => $serviceId))->update(array('service_status' => 0));
                return array('status' => true, 'msg' => '成功下架');
            } else {
                # 查询创建商品权限/创建商品数量 and service_status = 1
//                $createPro = Db::table('biz')
//                    ->field('create_pro,create_pro_num,
//                    (select count(id) from service where biz_pid = ' . $this->bizId . ' and audit_status != 3 and is_del = 2) exist_num')
//                    ->where(array('id' => $this->bizId))
//                    ->find();
//                $createPro['surplus_num'] = intval($createPro['create_pro_num']) - intval($createPro['exist_num']);
//                if ($createPro['surplus_num'] <= 0) {
//                    return array('status' => false, 'msg' => '服务创建已达上限,请联系管理员');
//                }
                # 状态修改为审核中
                Db::table('service')->where(array('id' => $serviceId))->update(array('audit_status' => 1));
                # 添加修改审核信息
                $auditId = Db::table('audit_creation')->insertGetId(array(
                    'type' => $info['addType'],
                    'pid' => $serviceId,
                    'biz_id' => $this->bizId,
                    'state' => 1,
                    'add_time' => date('Y-m-d H:i:s'),
                    'mark' => 2
                ));
                $this->_Redis->hSetJson('BizCreation', strval($auditId), $info);
                return array('status' => true, 'msg' => '已提交审核');
            }
            # service信息修改
            $service_re = Db::table('service')
                ->where(array('id' => $serviceId))
                ->update(array(
                    'service_title' => $info['service_title'],//服务名称
                    'service_class_id' => $info['service_class_id'],//服务分类id
                    'class_pid' => $info['class_pid'],//最高级分类id
                    'service_keyborder' => $service_keyborder,//关键词
                    'service_statement' => $info['service_statement'],//声明
                    'is_car_level' => $info['is_car_level'],//是否按车型设置价格
                    'service_time' => $info['service_time'],//服务时长
                    'is_discount' => $info['is_discount'],//是否打折
                    'discount_type' => $info['discount_type'],//折扣类型
                    'is_display' => $info['is_display'],//展示状态
                    'is_maintain' => $info['is_maintain'],//是否关联保养记录
                    'is_repair' => $info['is_repair'],//是否关联维修记录
                    'is_warranty' => $info['is_warranty'],//是否关联质保记录
                    'service_status' => $info['service_status'],//上下架状态
                    'service_image' => $info['service_image'],//缩略图
                    'service_picurl' => $info['service_picurl'],//banner
                    'service_context' => $info['service_context'],//详情图
                ));
            # 修改门店服务价格
            foreach ($info['biz_price'] as $k => $v) {
                Db::table('service_car_mediscount')
                    ->where(array('id' => $v['id']))
                    ->update(array('discount' => $v['discount']));
            }
            # 修改线上服务价格
            foreach ($info['biz_price'] as $k => $v) {
                Db::table('service_car_mediscount')
                    ->where(array('id' => $v['id']))
                    ->update(array('discount' => $v['discount']));
            }
        } else {
            # 信息添加
# 查询创建商品权限/创建商品数量 and service_status = 1
            $createPro = Db::table('biz')
                ->field('create_pro,create_pro_num,
                (select count(id) from service where biz_pid = ' . $this->bizId . ' and audit_status != 3 and is_del = 2) exist_num')
                ->where(array('id' => $this->bizId))
                ->find();
            $createPro['surplus_num'] = intval($createPro['create_pro_num']) - intval($createPro['exist_num']);
            if ($createPro['surplus_num'] <= 0) {
                return array('status' => false, 'msg' => '服务创建已达上限,请联系管理员');
            }
            # service信息添加
            $service_id = Db::table('service')
                ->insertGetId(array(
                    'service_title' => $info['service_title'],//服务名称
                    'service_class_id' => $info['service_class_id'],//服务分类id
                    'class_pid' => $info['class_pid'],//最高级分类id
                    'service_keyborder' => $service_keyborder,//关键词
                    'service_statement' => $info['service_statement'],//声明
                    'is_car_level' => $info['is_car_level'],//是否按车型设置价格
//                    'service_time' => $info['service_time'],//服务时长
//                    'is_discount' => $info['is_discount'],//是否打折
//                    'discount_type' => $info['discount_type'],//折扣类型
                    'is_display' => $info['is_display'],//展示状态
                    'is_maintain' => $info['is_maintain'],//是否关联保养记录
                    'is_repair' => $info['is_repair'],//是否关联维修记录
                    'is_warranty' => $info['is_warranty'],//是否关联质保记录
                    'audit_status' => 1,//审核状态 1=>审核中
                    'service_status' => 1,//上下架状态
                    'service_image' => $info['service_image'],//缩略图
//                    'service_picurl' => $info['service_picurl'],//banner
//                    'service_context' => $info['service_context'],//详情图
                    'add_type' => $info['addType'],
                    'biz_pid' => $this->bizId,
                    'relation_eva' => 2,
                    'is_relation' => 1,//是否关联服务  1是 2否
                    'service_pid' => 9 // 服务关联普洗服务
                ));
            # service_biz 信息添加
            Db::table('service_biz')
                ->insert(array(
                    'biz_id' => $this->bizId,
                    'service_id' => $service_id
                ));
            # service_car_mediscount 信息添加
            $priceArr = array();
            # 门店价格
            if ($info['is_car_level'] == 1) {
                # 按车型设置价格
                foreach ($info['biz_price'] as $k => $v) {
                    array_push($priceArr, array(
                        'service_id' => $service_id,
                        'car_level_id' => $v['car_level_id'],
                        'discount' => $v['discount'],
                        'service_type' => 2,
                        'biz_id' => $this->bizId
                    ));
                    array_push($priceArr, array(
                        'service_id' => $service_id,
                        'car_level_id' => $v['car_level_id'],
                        'discount' => $v['discount'],
                        'service_type' => 1,
                        'biz_id' => $this->bizId
                    ));
                }
            } else {
                # 不按车型设置价格
                foreach ([1, 2, 3] as $k => $v) {
                    array_push($priceArr, array(
                        'service_id' => $service_id,
                        'car_level_id' => $v,
                        'discount' => $info['biz_price'],
                        'service_type' => 2,
                        'biz_id' => $this->bizId
                    ));
                    array_push($priceArr, array(
                        'service_id' => $service_id,
                        'car_level_id' => $v,
                        'discount' => $info['biz_price'],
                        'service_type' => 1,
                        'biz_id' => $this->bizId
                    ));
                }
            }
            # 线上价格
//            if ($info['is_car_level'] == 1) {
//                # 按车型设置价格
//                foreach ($info['online_price'] as $k => $v) {
//                    array_push($priceArr, array(
//                        'service_id' => $service_id,
//                        'car_level_id' => $v['car_level_id'],
//                        'discount' => $v['discount'],
//                        'service_type' => 1,
//                        'biz_id' => $this->bizId
//                    ));
//                }
//            } else {
//                # 不按车型设置价格
//                foreach ([1, 2, 3] as $k => $v) {
//                    array_push($priceArr, array(
//                        'service_id' => $service_id,
//                        'car_level_id' => $v,
//                        'discount' => $info['online_price'],
//                        'service_type' => 1,
//                        'biz_id' => $this->bizId
//                    ));
//                }
//            }
            Db::table('service_car_mediscount')->insertAll($priceArr);
            # service_mediscount 信息添加
            if ($info['is_discount'] == 1) {
                $discountArr = array();
                # 打折
                $level_discount = Db::table('level_discount')
                    ->field('level_id,type,discount')
                    ->where(array('type' => $info['discount_type']))->select();
                foreach ($level_discount as $k => $v) {
                    array_push($discountArr, array(
                        'service_id' => $service_id,
                        'member_level' => $v['level_id'],
                        'discount' => $v['discount'],
                        'discount_type' => $info['discount_type']
                    ));
                }
                Db::table('service_mediscount')->insertAll($discountArr);
            } else {
                # 不打折
                $member_level = Db::table('member_level')->field('id')->select();
                $discountArr = array();
                foreach ($member_level as $k => $v) {
                    array_push($discountArr, array(
                        'service_id' => $service_id,
                        'member_level' => $v['id'],
                        'discount' => 1,
                        'discount_type' => 1
                    ));
                }
                Db::table('service_mediscount')->insertAll($discountArr);
            }
            # 关联保养记录信息添加
            if ($info['is_maintain'] == 1) {
                Db::table('service_log')->insert(array(
                    'service_id' => $service_id,
                    'log_title' => $info['maintain_log']['log_title'],
                    'log_validity' => $info['maintain_log']['log_validity'],
                    'log_kilometers' => $info['maintain_log']['log_kilometers'],
                    'log_type' => 1,
                    'log_time' => date('Y-m-d H:i:s')
                ));
            }
            # 关联维修记录信息添加
            if ($info['is_repair'] == 1) {
                Db::table('service_log')->insert(array(
                    'service_id' => $service_id,
                    'log_title' => $info['repair_log']['log_title'],
                    'log_type' => 2,
                    'log_time' => date('Y-m-d H:i:s')
                ));
            }
            # 关联质保记录信息添加
            if ($info['is_warranty'] == 1) {
                Db::table('service_log')->insert(array(
                    'service_id' => $service_id,
                    'log_validity' => $info['warranty_log']['log_validity'],
                    'log_kilometers' => $info['warranty_log']['log_kilometers'],
                    'log_scope' => $info['warranty_log']['log_scope'],
                    'log_type' => 3,
                    'log_time' => date('Y-m-d H:i:s')
                ));
            }
            # 添加创建审核信息
            Db::table('audit_creation')->insertGetId(array(
                'type' => $info['addType'],
                'pid' => $service_id,
                'biz_id' => $this->bizId,
                'state' => 1,
                'add_time' => date('Y-m-d H:i:s'),
                'mark' => 1
            ));
            # 完成上架服务任务
            TaskService::finishDayTask($this->bizId, 1);
            return array('status' => true, 'msg' => '已提交审核');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 删除 商品/服务 信息
     */
    function delInfo()
    {
        # 接收服务/商品 id
        $id = input('post.id');
        # 接收类型 1=>商品 2=>服务
        $type = input('post.type');
        if (empty($id)) {
            return array('status' => false, 'msg' => '系统错误-003');
        }
        if (empty($type)) {
            return array('status' => false, 'msg' => '系统错误-004');
        }
        if ($type == 1) {
            # 删除商品
            $re = Db::table('service')->where(array('id' => $id))->update(array('is_del' => 1));
        } else {
            # 删除服务
            $re = Db::table('service')->where(array('id' => $id))->update(array('is_del' => 1));
        }
        if ($re) {
            return array('status' => true, 'msg' => '删除成功');
        } else {
            return array('status' => false, 'msg' => '系统错误-删除失败');
        }
    }

    function setShowRecommend()
    {
        $id = input('post.id');
        $show_recommend_title = input('post.title');
        $n = mb_strlen($show_recommend_title);
        if($n<4){
            return array('status' => false, 'msg' => '最少输入四个字');
        }
        if($n>9){
            return array('status' => false, 'msg' => '最多输入九个字');
        }
        if (!empty($id) and !empty($show_recommend_title)) {
            Db::table('service')->where(array('id' => $id))->update(array('show_recommend' => 1, 'show_recommend_title' => $show_recommend_title));
            Db::table('service')->where(array('biz_pid' => $this->bizId))->where("id != $id")->update(array('show_recommend' => 2, 'show_recommend_title' => ''));
            return array('status' => true, 'msg' => '修改成功');
        } else {
            return array('status' => false, 'msg' => '请完善信息');
        }
    }
}
